package zmee.pur.src.formplugin;

import com.alibaba.excel.util.ObjectUtils;
import com.kingdee.util.StringUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.RefObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.tx.TX;
import kd.bos.db.tx.TXHandle;
import kd.bos.entity.operate.Submit;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.ConfirmTypes;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.scm.pds.common.enums.BidOpenStatusEnums;
import kd.scm.src.common.util.SrcProjectUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2022/12/04/18:47
 * @Description: 首次招标流程在资信评审环节，根据供应商的投标情况，控制流程是否能继续。
 * 点击【提交】按钮触发校验逻辑，若“资审状态”字段为“已评分”且“资审结果”字段为“资审合格”的供应商数量大与等于三家，则流程继续；否则流程终止并自动下推新流程。
 */
public class AptitudeAuditSubmitCheckPlugin extends AbstractBillPlugIn {

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        if (args.getSource() instanceof Submit) {
            //查询资质后审结果【资审状态】为“已评分”且【资审结果】为“资审合格”的供应商数量
            Long id = (Long) this.getModel().getValue("id");
            QFilter filter = new QFilter("parentid", "=", id).and("entryentity.isaptitude", "=", "1").and("scoretask.bizstatus", "=", "D");
            int supplierCount = QueryServiceHelper.query("src_aptituderesult2", "id", filter.toArray()).size();
            //查询项目启动【是否多次招标】
            QFilter filter1 = new QFilter("id", "=", id);
            DynamicObject project = QueryServiceHelper.queryOne("src_project", "id,zmee_dczb", filter1.toArray());
            boolean dczb = project.getBoolean("zmee_dczb");
            if (supplierCount < 3) {
                FormOperate operate = (FormOperate) args.getSource();
                if (dczb) {
                    if (supplierCount < 2) {
                        RefObject<String> afterConfirm = new RefObject<>();
                        if (!operate.getOption().tryGetVariableValue("afterconfirm", afterConfirm)) {
                            ConfirmCallBackListener callBack = new ConfirmCallBackListener("repeatedlybidopen", this);
                            Map<Integer, String> btnNameMaps = new HashMap<>(2);
                            btnNameMaps.put(2, "取消");
                            btnNameMaps.put(6, "流程终止");
                            this.getView().showConfirm("该流程为多次招标流程，资审合格供应商数量不符合开标条件，请确认供应商资审结果。", "", MessageBoxOptions.OKCancel,
                                    ConfirmTypes.Default, callBack, btnNameMaps);
                            args.setCancel(true);
                        }
                    }
                } else {
                    ConfirmCallBackListener callBack = new ConfirmCallBackListener("bidopen", this);
                    Map<Integer, String> btnNameMaps = new HashMap<>(2);
                    btnNameMaps.put(2, "取消");
                    btnNameMaps.put(6, "流程终止");
                    this.getView().showConfirm("资审合格供应商数量不符合开标条件，请确认供应商资审结果情况。", "", MessageBoxOptions.OKCancel, ConfirmTypes.Default,
                            callBack, btnNameMaps);
                    args.setCancel(true);
                }
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent evt) {
        super.confirmCallBack(evt);
        String callBackId = evt.getCallBackId();
        MessageBoxResult result = evt.getResult();
        if (StringUtils.equals("bidopen", callBackId)) {
            if (MessageBoxResult.Yes.equals(result)) {
                ConfirmCallBackListener callBack = new ConfirmCallBackListener("termination", this);
                this.getView().showConfirm("确认要终止流程吗？", MessageBoxOptions.OKCancel, callBack);
            }
        } else if ("termination".equals(callBackId)) {
            if (MessageBoxResult.Yes.equals(result)) {
                Long projectId = (Long) this.getModel().getValue("id");
                try (TXHandle h = TX.requiresNew()) {
                    try {
                        //重新发起流程
                        //BotpUtil.pushAndSave("src_project", "src_project", projectId);
                        //项目成员
                        DynamicObject projectManObj = BusinessDataServiceHelper.loadSingle("src_project_man",
                                "entryentity,entryentity" + ".entrystatus", new QFilter[]{new QFilter("parentid", "=", projectId)});
                        DynamicObjectCollection entryentity = projectManObj.getDynamicObjectCollection("entryentity");
                        for (DynamicObject object : entryentity) {
                            object.set("entrystatus", "E");
                        }
                        SaveServiceHelper.save(new DynamicObject[]{projectManObj});
                        //标书编制
                        DynamicObject biddocObj = BusinessDataServiceHelper.loadSingle(projectId, "src_biddoc", "bizstatus");
                        biddocObj.set("bizstatus", "E");
                        SaveServiceHelper.save(new DynamicObject[]{biddocObj});
                        //招标公告
                        DynamicObject publishnoticeObj = BusinessDataServiceHelper.loadSingle(projectId, "src_publishnotice", "bizstatus");
                        publishnoticeObj.set("bizstatus", "E");
                        SaveServiceHelper.save(new DynamicObject[]{publishnoticeObj});
                        //收费
                        DynamicObject payManageObj = BusinessDataServiceHelper.loadSingle(projectId, "src_paymanage", "bizstatus");
                        payManageObj.set("bizstatus", "E");
                        SaveServiceHelper.save(new DynamicObject[]{payManageObj});
                        //开标准备
                        DynamicObject bidOpenObj = BusinessDataServiceHelper.loadSingle(projectId, "src_bidopen", "bizstatus");
                        bidOpenObj.set("bizstatus", "E");
                        SaveServiceHelper.save(new DynamicObject[]{bidOpenObj});
                        //资质后审
                        DynamicObject aptitudeAuditObj = BusinessDataServiceHelper.loadSingle(projectId, "src_aptitudeaudit2", "bizstatus");
                        aptitudeAuditObj.set("bizstatus", "E");
                        SaveServiceHelper.save(new DynamicObject[]{aptitudeAuditObj});
                        //项目启动
                        DynamicObject projectObj = BusinessDataServiceHelper.loadSingle(projectId, "src_project", "currentnode," +
                                "terminalnode,openstatus,bizstatus,bidname,org,source,srcbillid");
                        projectObj.set("terminalnode", projectObj.get("currentnode"));
                        projectObj.set("currentnode", 1291999207766400000L);
                        projectObj.set("openstatus", BidOpenStatusEnums.TERMINATED.getValue());
                        projectObj.set("bizstatus", "E");
                        SaveServiceHelper.save(new DynamicObject[]{projectObj});
                        this.getView().invokeOperation("refresh");
                        //下查项目启动单
                        String sourceTypeNumber = ((DynamicObject) this.getModel().getValue("sourcetype")).getString("number");
                        DynamicObject srcType = (DynamicObject) this.getModel().getValue("srctype");
                        String billNo = (String) this.getModel().getValue("billno");
                        long newBillId = SrcProjectUtil.createNewBillId("src_project", sourceTypeNumber, srcType.getLong("id"), true);
                        DynamicObject object = BusinessDataServiceHelper.loadSingle(newBillId, "src_project");
                        if (ObjectUtils.isEmpty(object)) {
                            h.markRollback();
                            this.getView().showMessage("新的项目启动单生成失败！");
                            return;
                        }
                        setProjectPropValue(projectId, projectObj, billNo, newBillId, object);
                        this.getView().showMessage("新的项目启动单项目编号是：" + object.getString("billno"));
                    } catch (Throwable e) {
                        h.markRollback();
                        throw e;
                    }
                }
            }
        } else if ("repeatedlybidopen".equals(callBackId)) {
            /*if (MessageBoxResult.Ignore.equals(result)) {
                OperateOption operateOption = OperateOption.create();
                operateOption.setVariableValue("afterconfirm", "true");
                this.getView().invokeOperation("submit", operateOption);
            } else */
            if (MessageBoxResult.Yes.equals(result)) {
                ConfirmCallBackListener callBack = new ConfirmCallBackListener("termination", this);
                this.getView().showConfirm("确认要终止流程吗？", MessageBoxOptions.OKCancel, callBack);
            }
        }
    }

    private void setProjectPropValue(Long projectId, DynamicObject projectObj, String billNo, long newBillId, DynamicObject object) {
        object.set("zmee_dczb", true);
        object.set("bidname", projectObj.get("bidname"));
        object.set("org", projectObj.get("org"));
        object.set("source", projectObj.get("source"));
        object.set("srcbillid", projectObj.get("srcbillid"));
        SaveServiceHelper.save(new DynamicObject[]{object});

        DynamicObject sourceProjectBaseObj = BusinessDataServiceHelper.loadSingle(projectId, "src_project_base");
        DynamicObject targetProjectBaseObj = BusinessDataServiceHelper.loadSingle(newBillId, "src_project_base");
        //投标截止时间
        targetProjectBaseObj.set("stopbiddate", sourceProjectBaseObj.get("stopbiddate"));
        targetProjectBaseObj.set("decisiontype", sourceProjectBaseObj.get("decisiontype"));
        targetProjectBaseObj.set("taxtype", sourceProjectBaseObj.get("taxtype"));
        SaveServiceHelper.save(new DynamicObject[]{targetProjectBaseObj});

        DynamicObject sourceType = (DynamicObject) this.getModel().getValue("sourcetype");
        String number = sourceType.getString("number");
        DynamicObject sourceProjectRuleObj = BusinessDataServiceHelper.loadSingle(projectId, "src_project_rule");
        DynamicObject targetProjectRuleObj = BusinessDataServiceHelper.loadSingle(newBillId, "src_project_rule");
        targetProjectRuleObj.set("zmee_check", true);
        if ("C010405".equals(number)) {
            targetProjectRuleObj.set("winrule", sourceProjectRuleObj.getDynamicObject("winrule"));
            targetProjectRuleObj.set("ruleassess", sourceProjectRuleObj.get("ruleassess"));
            targetProjectRuleObj.set("winerqty", sourceProjectRuleObj.get("winerqty"));
            targetProjectRuleObj.set("biderqty", sourceProjectRuleObj.get("biderqty"));
            targetProjectRuleObj.set("scheme", sourceProjectRuleObj.getDynamicObject("scheme"));
            targetProjectRuleObj.set("otherruleassess", sourceProjectRuleObj.get("otherruleassess"));
            targetProjectRuleObj.set("remark", sourceProjectRuleObj.get("remark"));
            SaveServiceHelper.save(new DynamicObject[]{targetProjectRuleObj});
        } else if ("C010406".equals(number)) {
            targetProjectRuleObj.set("winrule", sourceProjectRuleObj.getDynamicObject("winrule"));
            targetProjectRuleObj.set("winerqty", sourceProjectRuleObj.get("winerqty"));
            targetProjectRuleObj.set("biderqty", sourceProjectRuleObj.get("biderqty"));
            targetProjectRuleObj.set("scheme", sourceProjectRuleObj.getDynamicObject("scheme"));
            targetProjectRuleObj.set("remark", sourceProjectRuleObj.get("remark"));
            targetProjectRuleObj.set("negotiaterule", sourceProjectRuleObj.getString("negotiaterule"));
            targetProjectRuleObj.set("topsupplier", sourceProjectRuleObj.get("topsupplier"));
            targetProjectRuleObj.set("zmee_tpspreads", sourceProjectRuleObj.get("zmee_tpspreads"));
            targetProjectRuleObj.set("extfilter", sourceProjectRuleObj.getDynamicObject("extfilter"));
            targetProjectRuleObj.set("sourcetype", sourceProjectRuleObj.getDynamicObject("sourcetype"));
            SaveServiceHelper.save(new DynamicObject[]{targetProjectRuleObj});
        } else if ("C010415".equals(number)) {
            targetProjectRuleObj.set("winrule", sourceProjectRuleObj.getDynamicObject("winrule"));
            targetProjectRuleObj.set("winerqty", sourceProjectRuleObj.get("winerqty"));
            targetProjectRuleObj.set("biderqty", sourceProjectRuleObj.get("biderqty"));
            targetProjectRuleObj.set("scheme", sourceProjectRuleObj.getDynamicObject("scheme"));
            targetProjectRuleObj.set("remark", sourceProjectRuleObj.get("remark"));
            targetProjectRuleObj.set("negotiaterule", sourceProjectRuleObj.getString("negotiaterule"));
            targetProjectRuleObj.set("topsupplier", sourceProjectRuleObj.get("topsupplier"));
            targetProjectRuleObj.set("zmee_csscoregap", sourceProjectRuleObj.get("zmee_csscoregap"));
            targetProjectRuleObj.set("extfilter", sourceProjectRuleObj.getDynamicObject("extfilter"));
            targetProjectRuleObj.set("sourcetype", sourceProjectRuleObj.getDynamicObject("sourcetype"));
            SaveServiceHelper.save(new DynamicObject[]{targetProjectRuleObj});
        }

        QFilter filter = new QFilter("parentid", "=", projectId);
        DynamicObject sourceObj = BusinessDataServiceHelper.loadSingle("src_purlist_stand", "id", filter.toArray());
        DynamicObject sourcePurListStandObj = BusinessDataServiceHelper.loadSingle(sourceObj.getPkValue(), "src_purlist_stand");
        DynamicObjectCollection entryEntity = sourcePurListStandObj.getDynamicObjectCollection("entryentity");

        QFilter filter1 = new QFilter("parentid", "=", newBillId);
        DynamicObject targetObj = BusinessDataServiceHelper.loadSingle("src_purlist_stand", "id", filter1.toArray());
        DynamicObject targetPurListStandObj = null;
        if (null == targetObj) {
            targetPurListStandObj = BusinessDataServiceHelper.newDynamicObject("src_purlist_stand");
        } else {
            targetPurListStandObj = BusinessDataServiceHelper.loadSingle(targetObj.getPkValue(), "src_purlist_stand");
        }

        targetPurListStandObj.set("parentid", newBillId);
        targetPurListStandObj.set("entitykey", "src_purlist_stand");
        targetPurListStandObj.set("curr", 1L);
        targetPurListStandObj.set("taxtype", sourcePurListStandObj.get("taxtype"));
        targetPurListStandObj.set("sumqty", sourcePurListStandObj.get("sumqty"));
        targetPurListStandObj.set("sumtax", sourcePurListStandObj.get("sumtax"));
        targetPurListStandObj.set("sumamount", sourcePurListStandObj.get("sumamount"));
        targetPurListStandObj.set("sumtaxamount", sourcePurListStandObj.get("sumtaxamount"));
        targetPurListStandObj.set("origin", sourcePurListStandObj.get("origin"));
        targetPurListStandObj.set("pentitykey", sourcePurListStandObj.get("pentitykey"));
        targetPurListStandObj.getDynamicObjectCollection("entryentity").clear();

        Map<String, List<DynamicObject>> listMap =
                entryEntity.stream().collect(Collectors.groupingBy(s -> s.get("material.number") + "_" + s.get("entryrcvorg.id") + "_" + s.get("srcbillno")));
        for (Map.Entry<String, List<DynamicObject>> listEntry : listMap.entrySet()) {
            List<DynamicObject> entry = listEntry.getValue();
            DynamicObject dynamicObject = entry.get(0);
            DynamicObjectCollection collection = targetPurListStandObj.getDynamicObjectCollection("entryentity");
            DynamicObject entity = collection.addNew();
            setValues(newBillId, billNo, dynamicObject, entity);
        }
        SaveServiceHelper.save(new DynamicObject[]{targetPurListStandObj});
    }

    private void setValues(Long projectId, String billNo, DynamicObject entry, DynamicObject entity) {
        entity.set("seq", entry.get("seq"));
        entity.set("packagename", entry.get("packagename"));
        entity.set("category", entry.get("category"));
        entity.set("material", entry.get("material"));
        entity.set("materialnane", entry.get("materialnane"));
        entity.set("materialmodel", entry.get("materialmodel"));
        entity.set("unit", entry.get("unit"));
        entity.set("qty", entry.get("qty"));
        entity.set("tax", entry.get("tax"));
        entity.set("turns", entry.get("turns"));
        entity.set("entrystatus", entry.get("entrystatus"));
        entity.set("currency", entry.get("currency"));
        entity.set("package", entry.get("package"));
        entity.set("project", projectId);
        entity.set("purlist", entry.get("purlist"));
        entity.set("bizamount", entry.get("bizamount"));
        entity.set("rank", entry.get("rank"));
        entity.set("sysresult", entry.get("sysresult"));
        entity.set("result", entry.get("result"));
        entity.set("orderratio", entry.get("orderratio"));
        entity.set("bidmaterial", entry.get("bidmaterial"));
        entity.set("entryparentid", projectId);
        entity.set("pkgamount", entry.get("pkgamount"));
        //entity.set("suppliertype", entry.get("suppliertype"));
        //entity.set("supplier", entry.get("supplier"));
        //entity.set("suppliername", entry.get("suppliername"));
        entity.set("exratetable", entry.get("exratetable"));
        entity.set("exratedate", entry.get("exratedate"));
        entity.set("exrate", entry.get("exrate"));
        entity.set("quotation", entry.get("quotation"));
        entity.set("entryrcvorg", entry.get("entryrcvorg"));
        entity.set("taxitem", entry.get("taxitem"));
        entity.set("taxrate", entry.get("taxrate"));
        entity.set("zmee_easnumber", entry.get("zmee_easnumber"));
        entity.set("zmee_easentry", entry.get("zmee_easentry"));

        entity.set("effectdate", entry.get("effectdate"));
        entity.set("duedate", entry.get("duedate"));
        entity.set("org", entry.get("org"));
        entity.set("baseunit", entry.get("baseunit"));
        entity.set("reqsource", entry.get("reqsource"));
        entity.set("srcbillno", billNo);
    }
}
